/**
 * @file main.c
 * @brief Single-threaded server.
 * @author Leonardo Guilherme de Freitas
 * 
 * Implementação de um servidor single-threaded com suporte
 * a multiplos usuários.
 * 
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <signal.h>

#include "webserver.h"
#include "lib/server.h"
#include "lib/timeutil.h"

char * serverpath;
int serverpathlen;
int interrupted = 0;

void intrhandler(int sig)
{
  interrupted = 1;
}

void print_usage(const char *cmd)
{
  fprintf(stderr, "Uso:\n"
    "\t%s <porta> <raiz> [velocidade]\n",
    cmd
  );
}


int main(int argc, char ** argv)
{
  int quit = 0;
  size_t bps = 0;
  long begin = 0, end = 0, delta = 0;
  
  server s;
  struct timespec start;
  
  if (argc < 3)
  {
    print_usage(argv[0]);
    exit(1);
  }
  if (argc >= 4)
    bps = atoi(argv[3]);
   
  
  serverinit(&s, atoi(argv[1]), bps);
  serverpath = realpath(argv[2], 0);
  if (serverpath == 0)
  {
    perror("Nao foi possivel acessar o path raiz");
    return 1;
  }
  serverpathlen = strlen(serverpath) + 1;
  printf("Canonical server path: %s\n", serverpath);
  printf("Speed control: %d bytes per second\n", bps);
    
  s.update = server_lite_update;
  s.quit = server_lite_quit;
  
  signal(SIGINT, intrhandler);
  
  // main loop
  while (!quit && !interrupted) {
    
    if (s.clients == 0 || bps == 0) /* sem cliente ainda ou sem bps */
      perai(10);
    else
    {
      perai(1000000000-delta);
    }
    
    begin = elapsed(&start);
    quit = serverupdate(&s);
    end = elapsed(&start);
    delta = end-begin;
  }
  
  serverdestroy(&s);
  free(serverpath);

  return 0;
}